#include "LegacyMotionImporter.h"
#include "LegacyMotionImporterDialog.h"

#include <MMM/XMLTools.h>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>

using namespace MMM;

LegacyMotionImporter::LegacyMotionImporter(QWidget* widget) :
    MotionHandler(MotionHandlerType::IMPORT, "Import legacy mmm motion file"),
    widget(widget)
{
}

std::string LegacyMotionImporter::getName() {
    return NAME;
}

void LegacyMotionImporter::handleMotion(MotionList motions) {
    QSettings settings;
    std::string motionFilePath = QFileDialog::getOpenFileName(widget, QString::fromStdString(getDescription()), settings.value("motion/searchpath", "").toString(), QString::fromStdString("legacy motion files (*.xml)")).toStdString();
    if (!motionFilePath.empty()) {
        try {
            settings.setValue("motion/searchpath", QString::fromStdString(XML::getPath(motionFilePath)));
            LegacyMotionConverterPtr converter(new LegacyMotionConverter(motionFilePath));
            LegacyMotionImporterDialog* dialog = new LegacyMotionImporterDialog(converter, widget);
            settings.setValue("motion/path", QString::fromStdString(motionFilePath));
            settings.setValue("motion/type", QString::fromStdString("LegacyMMM"));
            emit openMotions(dialog->getMotions());
        } catch (MMM::Exception::MMMException& e) {
            QMessageBox* msgBox = new QMessageBox(widget);
            msgBox->setText(QString::fromStdString(e.what()));
            msgBox->exec();
        }
    }
}
